<?php

namespace Parser\Separator;

use Parser\Enquiry;
use Parser\Parser;
use Parser\Repetition;

class TIAN implements BaseSeparator
{
    public static $ApiKindList = [
        3000 => '01', //车损
        4000 => '02', //三者
        5002 => '041', //司机
        5001 => '044', //乘客
        30002 => '83',
        3002 => '21',
        30004 => '85',
        40002 => '25',
        50022 => '86',
        4001 => '19',
        50012 => '87',
    ];

    public function interpreter(array $array, $parser)
    {
        if ($this->error($array, $parser)) {
            return;
        }

        $parser->result = $this->analysis($array);
    }

    /**
     *错误解析
     * Author:ls
     *
     * @param $array
     * @param parser $parser
     * @return bool
     */
    public function error(&$array, $parser): bool
    {

        if ($array['code'] != '0000') {
            $parser->message = $array['message'];
            $parser->code = '500';
            return true;
        }

        if ($message = $array['message'] ?? false) {
            if (!preg_match('/车险报价成功,报价单号:/', $message)) {
                $parser->message = $message;
                $parser->code = '500';
                return true;
            }
        }

        if (!$array['data']['kindList'] ?? false) {
            $parser->message = '参数错误，重新请求';
            $parser->code = '500';
            return true;
        }
        return false;
    }


    public function analysis($array): array
    {
        $enquiry = new Enquiry();

        foreach ($array['data']['kindList'] as $value) {
            if ($value['riskcode'] == '0881') {
                $enquiry->setTaxTotal($array['data']['carTaxPlat']['sumTax'] ?? '0');
                $enquiry->setTaxTotal($array['data']['carTaxPlat']['annualTaxDue'] ?? '0');
                $enquiry->setTCITotal($value['premium']);
                $enquiry->setTCIPremium($value['basepremium']);
            } elseif ($value['riskcode'] == '0888') {
                $enquiry->setVCIDiscount($value['discount']);
                $enquiry->VCITotalAppend($value['premium']);
                $enquiry->VCIPremiumAppend($value['basepremium']);

                $coverages['code'] = (string)array_search($value['kindcode'], self::$ApiKindList);
                $coverages['shortName'] = $value['kindname'];
                $coverages['insuredDesc'] = (string)$value['amount'] ?? '';
                $coverages['total'] = (string)$value['premium'];
                $enquiry->setVCICoverages($coverages);
            }
        }

        $enquiry->setTotal();
        //无赔款优待系数NCD $array['data']['cPlatformVO']['commericBastPlat']['noAmountAdjustRatio']
        if (!empty($array['data']['cPlatformVO']['commericBastPlat']['noAmountAdjustRatio'])) {
            $enquiry->setNCDRate($array['data']['cPlatformVO']['commericBastPlat']['noAmountAdjustRatio'] ?? '0');
        }
        if ($repeat = $array['prpReInsureItems'] ?? []) {
            $enquiry->failure();
            if (count($repeat) >= 1) {
                $enquiry->setErrorTip('商业险重复投保');
            }
        }
        $enquiry->success();

        return $enquiry->get();
    }

    //数据解析
    public function repetition($array): Repetition
    {
        $repetition = new Repetition();

        $repetition->setLastSignTime($array['data']['trcPlatformVO']['bzBastPlat']['lastBillDate'] ?? '');
        $repetition->setLastStartAt($array['data']['cPlatformVO']['lastPolicyPlat']['lastPolicyEffectiveDate'] ?? '');
        $repetition->setLastEndTime($array['data']['cPlatformVO']['lastPolicyPlat']['lastPolicyExpireDate'] ?? '');
        $repetition->setLicense($array['data']['vehicledto']['licenseno'] ?? '');

        //初始设置
        $repetition->setLastPolicy($array['data']['calculateno'] ?? '');
        $repetition->setLastCompany($array['data']['trcPlatformVO']['bzClaimPlat'][0]['insurerCode'] ?? '');

        $coverage = [];

        if ($message = $array['message'] ?? false) {
            preg_match('/上年投保险种：(.*)<br>/', $message, $matches);
            if (count($matches) >= 2) {
                $str = trim($matches[1]);
                $coverageArr = explode(';', $str);

                foreach ($coverageArr as $item) {
                    if (!$item) {
                        continue;
                    }
                    $coverage[] = mb_substr($item, mb_strrpos($item, ':') + 1);
                }
            }
            //
            preg_match('/重复投保保单号：(\w*),/', $message, $matches2);
            if (count($matches2) >= 2) {
                $repetition->setLastPolicy($matches2[1]);
            }
            //
            preg_match('/保险公司代码：(\w*),/', $message, $matches3);
            if (count($matches3) >= 2) {
                $repetition->setLastCompany($matches3[1]);
            }

        }

        $repetition->setLastCoverage($coverage);
        if ($repetition->getLastCompany()) {
            $repetition->setStatus('success');
        }
        return $repetition;
    }
}

